<template>
    <ul class="pagination m-b-0" v-if="pageCount > 0">
        <li :class="{'disabled': page == 1}" @click="decrease"> <a href="javascript:void(0)"><i class="fif fif-angle-left" ></i></a> </li>
        <li  :key="'page' + index" v-for="(num, index) in pageArr" :class="{'active': num == page}" @click="goTopage(num)">
            <a href="javascript:void(0)">{{num}}</a>
        </li>
        <li :class="{'disabled': page == pageCount}"  @click="add"><a href="javascript:void(0)"><i class="fif fif-angle-right"></i></a> </li>
    </ul>
</template>

<script>
    export default {
        name: "Pagination",
        created() {},
        props: {
            // 当前页数
            page: {
                type: Number,
                default: 1,
            },
            // 总页数
            pageCount: {
                type: Number,
                default: 0,
            },
            // 中间显示个数
            limit: {
                type: Number,
                default: 6
            },
            max: { // 大于该数时显示缩略图
                type: Number,
                default: 12
            }
        },
        computed: {
            pageArr () {
                if (this.limit === -1) return 0;

                if (this.limit === 0) return this.pageCount;
                let current = this.page;
                let last = this.pageCount;
                let delta = this.limit;
                let left = current - delta;
                let right = current + delta + 1;
                let range = [];
                let pages = [];
                let l;
                for (let i = 1; i <= last; i++) {
                    if (i === 1 || i === last || (i >= left && i < right)) {
                        range.push(i);
                    }
                }
                
                range.forEach( (i) => {
                    if (l) {
                        if (i - l === 2) {
                            pages.push(l + 1);
                        } else if (i - l !== 1) {
                            pages.push('...');
                        }
                    }
                    pages.push(i);
                    l = i;
                });
                return pages;
            }
        },
        methods: {
            add() {
                if (this.page == this.pageCount) return
                this.$emit('change', this.page + 1)
            },
            decrease() {
                if (this.page == 1) return
                this.$emit('change', this.page - 1)
            },
            goTopage(page) {
                if (page == '...' || page == this.page) return
                this.$emit('change', page)
            }
        }
    }
</script>

<style scoped>

</style>